/*****************************************************************************
 * Copyright (c) 2010 -, Anders All rights reserved
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 *  Contact: Anders Uddenberg (anders.uddenberg@gmail.com)
 * 
 *
 ****************************************************************************/
package org.easypr.organizer.client.presenter;

import org.easypr.organizer.client.BackboneServiceAsync;
import org.easypr.organizer.client.MyUserService;
import org.easypr.organizer.client.MyUserServiceAsync;
import org.easypr.organizer.client.event.DisplayInformationEvent;
import org.easypr.organizer.shared.MyContact;
import org.easypr.organizer.shared.MyUser;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

// TODO: Auto-generated Javadoc
/**
 * The Class CreatePresenter.
 */
public class CreatePresenter implements Presenter {

	/**
	 * Define the interface the view needs to implement.
	 * 
	 * @author Anders
	 */
	public interface Display {
		
		/**
		 * Sets the data.
		 * 
		 */
		void setData();

		/**
		 * As widget.
		 * 
		 * @return the widget
		 */
		Widget asWidget();
		
		/**
		 * Gets the name input.
		 *
		 * @return the name input
		 */
		TextBox getNameInput();
		
		/**
		 * Gets the email input.
		 *
		 * @return the email input
		 */
		TextBox getEmailInput();
		
		/**
		 * Gets the cellphone input.
		 *
		 * @return the cellphone input
		 */
		TextBox getCellphoneInput();
		
		/**
		 * Gets the workphone input.
		 *
		 * @return the workphone input
		 */
		TextBox getWorkphoneInput();
		
		/**
		 * Gets the workplace input.
		 *
		 * @return the workplace input
		 */
		TextBox getWorkplaceInput();
		
		/**
		 * Gets the background input.
		 *
		 * @return the background input
		 */
		TextArea getBackgroundInput();
		
		/**
		 * Gets the save button.
		 *
		 * @return the save button
		 */
		Button getSaveButton();
		
		/**
		 * Gets the cancel button.
		 *
		 * @return the cancel button
		 */
		Button getCancelButton();
		
		/**
		 * Update history.
		 */
		void updateHistory();
		
		/**
		 * Adds the to history.
		 *
		 * @param contact the contact
		 */
		void addToHistory(MyContact contact);
		
		/**
		 * Clear form.
		 */
		void clearForm();
	}

	/** The event bus. */
	private final HandlerManager eventBus;
	
	/** The backbone rpc. */
	private BackboneServiceAsync backboneRPC;
	
	/** The display. */
	private final Display display;

	//private String searchString;
	
	/**
	 * Instantiates a new menu presenter.
	 *
	 * @param backboneRPC the backbone rpc
	 * @param eventBus the event bus
	 * @param view the view
	 */
	public CreatePresenter(BackboneServiceAsync backboneRPC, HandlerManager eventBus, Display view) {
		this.backboneRPC = backboneRPC;
		this.eventBus = eventBus;
		this.display = view;
		bind();
	}
	
	/* (non-Javadoc)
	 * @see org.easypr.organizer.client.presenter.Presenter#go(com.google.gwt.user.client.ui.HasWidgets)
	 */
	@Override
	public void go(HasWidgets container) {
		container.clear();
		container.add(display.asWidget());
		bind();
		updateContent();
	}
	
	/**
	 * Bind.
	 */
	private void bind() {
		
		display.getNameInput().addBlurHandler(new BlurHandler() {
			public void onBlur(BlurEvent event) {
				if(display.getNameInput().getText().trim().length() == 0) {
					display.getNameInput().setText("Name*");
				}
			}
		});
		
		display.getNameInput().addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				if(display.getNameInput().getText().equals("Name*")) {
					display.getNameInput().setText("");
				}
			}
		});
		
		display.getWorkplaceInput().addBlurHandler(new BlurHandler() {
			public void onBlur(BlurEvent event) {
				if(display.getWorkplaceInput().getText().trim().length() == 0) {
					display.getWorkplaceInput().setText("Work place");
				}
			}
		});
		
		display.getWorkplaceInput().addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				if(display.getWorkplaceInput().getText().equals("Work place")) {
					display.getWorkplaceInput().setText("");
				}
			}
		});
		
		display.getWorkphoneInput().addBlurHandler(new BlurHandler() {
			public void onBlur(BlurEvent event) {
				if(display.getWorkphoneInput().getText().trim().length() == 0) {
					display.getWorkphoneInput().setText("Work phone");
				}
			}
		});
		
		display.getWorkphoneInput().addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				if(display.getWorkphoneInput().getText().equals("Work phone")) {
					display.getWorkphoneInput().setText("");
				}
			}
		});
		
		display.getCellphoneInput().addBlurHandler(new BlurHandler() {
			public void onBlur(BlurEvent event) {
				if(display.getCellphoneInput().getText().trim().length() == 0) {
					display.getCellphoneInput().setText("Cellphone");
				}
			}
		});
		
		display.getCellphoneInput().addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				if(display.getCellphoneInput().getText().equals("Cellphone")) {
					display.getCellphoneInput().setText("");
				}
			}
		});
		
		display.getEmailInput().addBlurHandler(new BlurHandler() {
			public void onBlur(BlurEvent event) {
				if(display.getEmailInput().getText().trim().length() == 0) {
					display.getEmailInput().setText("Email");
				}
			}
		});
		
		display.getEmailInput().addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				if(display.getEmailInput().getText().equals("Email")) {
					display.getEmailInput().setText("");
				}
			}
		});
		
		display.getCancelButton().addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				History.back();
			}
		});
		
		display.getSaveButton().addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				if(display.getSaveButton().isEnabled()) { // Ugly hack to get the event to fire once
					
				
					final String name = (display.getNameInput().getText().trim().equals("Name*") ? 
							"" : display.getNameInput().getText().trim());
					if(name.length() > 0) {
						display.getSaveButton().setEnabled(false);
						final String email = (display.getEmailInput().getText().trim().equals("Email") ?
								"" : display.getEmailInput().getText().trim());
						final String cellphone = (display.getCellphoneInput().getText().trim().equals("Cellphone") ?
								"" : display.getCellphoneInput().getText().trim());
						final String workphone = (display.getWorkphoneInput().getText().trim().equals("Work phone") ?
								"" : display.getWorkphoneInput().getText().trim());
						final String workplace = (display.getWorkplaceInput().getText().trim().equals("Work place") ?
								"" : display.getWorkplaceInput().getText().trim());
						final String background = display.getBackgroundInput().getText().trim();
						
						
						MyUserServiceAsync userRPC = GWT.create(MyUserService.class);
						
						AsyncCallback<MyUser> callback = new AsyncCallback<MyUser>() {
							public void onFailure(Throwable caught) {
								eventBus.fireEvent(new DisplayInformationEvent("Unable to proceed with the request!", DisplayInformationEvent.Severity.FAILURE));
							}

							public void onSuccess(MyUser user) {
								MyContact contact = new MyContact(user.getEmail(), name, email, cellphone, workphone, workplace, background);
								doSaveContact(contact);
							}
						};
						
						userRPC.getUser(callback);
						
					} else {
						eventBus.fireEvent(new DisplayInformationEvent("You need to give this contact a name!", DisplayInformationEvent.Severity.USER_ERROR));
					}
				}
			}
		});
	}
	
	/**
	 * Do save contact.
	 *
	 * @param contact the contact
	 */
	private void doSaveContact(MyContact contact) {
		
		AsyncCallback<MyContact> callback = new AsyncCallback<MyContact>() {
			public void onFailure(Throwable caught) {
				eventBus.fireEvent(new DisplayInformationEvent("Unable to save the contact!", DisplayInformationEvent.Severity.FAILURE));
			}

			public void onSuccess(MyContact contact) {
				// Add to history
				if(contact instanceof MyContact) {
					display.addToHistory(contact);
					display.updateHistory();
				
					// Clear form
					display.clearForm();
					eventBus.fireEvent(new DisplayInformationEvent("Contact saved successfully!", DisplayInformationEvent.Severity.SUCCESS));
				} 
			}
		};
		
		this.backboneRPC.saveContact(contact, callback);
	}
	
	/**
	 * Main function to update the content of the container.
	 */
	public void updateContent() {
		display.setData();
	}
}

